<template>
	<view style="margin: 10px;background-color: #fff;border-radius: 10px;">
		<!-- <image class="logo" src="/static/logo.png"></image> -->
	<!-- <view class="uni-reture">
		<uni-icons type="back" size="26" @click="goBack"></uni-icons>
		</view> -->
		<view style="padding: 15px;padding-right: 15px;">
			<uni-forms ref="baseForm" :rules="rules" :modelValue="FormData">
				<uni-forms-item label="整改人:">
					<uni-easyinput v-model="userName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="整改时间:" required name="abarbeitungTime">
					<uni-datetime-picker type="datetime" :clear-icon="false" v-model="FormData.abarbeitungTime" @maskClick="maskClick" />
				</uni-forms-item>
				<uni-forms-item label="问题描述:">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.description" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="原因:" required name="cause">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.cause" placeholder="请输入无法处理原因"/>
				</uni-forms-item>
				<uni-forms-item label="改前图片:">
					<image class="uni-imge"
							v-for="(item, index) in FormData.frontImageListData"
							:key="index" 
							 @click="previewImage(item.url)" 
							 :src='item.url'></image>
				</uni-forms-item>
			</uni-forms>
			<view class="layout-form-btn" style="margin-top: 10px;" >
				<button class="uni-button-color" type="primary" @click="clickInter('baseForm')">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { post, fileUpLoad, postForm } from '../../../utils/request.js';
	export default {
		data() {
			return {
				// 校验规则
				rules: {
					cause: {
						rules: [{
							required: true,
							errorMessage: '请输入无法处理原因'
						}]
					},
					abarbeitungTime: {
						rules: [{
							required: true,
							errorMessage: '请选择整改时间'
						}]
					},
				},
				imageStyles:{
					width:70,
					height:70,
					border:{
						color:"rgb(238, 238, 238)",
						width:2,
						style:'dashed',
						radius:'2px'
					}
				},
				id: '',
				abarbeitungTime: Date.now(),
				userInfor: uni.getStorageSync('userInfor'),
				userId: '',
				title: '',
				userName: '',
				FormData: {
					checkUser: '',
					createTime: '',
					abarbeitungTime: Date.now(),
					description: '',
					frontImage: '',
					name: '',
					workshopId: '',
					workshopareaId: '',
					cause: ''
				},
				shopOption: [],
				spaceOption: [],
				selectTab: 0,
				selected: {
					'点检问题': 0
				}
			}
		},
		onShow() {
			this.FormData.abarbeitungTime = Date.now()
			this.userInfor = uni.getStorageSync('userInfor')
			this.userName = this.userInfor.name
			this.userId = this.userInfor.userId
		},
		onLoad(options) {
			//console.log(options.id)
			//debugger
			this.id = options.id
			this.getData()
		},
		methods: {
			clickInter(ref){
				this.$refs[ref].validate().then(res => {
					let saveData = {}
					saveData = {
						abarbeitungTime: this.FormData.abarbeitungTime,
						abarbeitungUserId: this.userId,
						cause: this.FormData.cause,
						id: this.id
					}
					post('/problem/submit/error', saveData)
					      .then(data => {
							  if(data.code == 200) {
								  uni.showToast({
								  	title: '数据保存成功！',
								  	duration: 1000
								  });
								uni.switchTab({
					                url: '/pages/work/index'
					            });
							  } else {
								  uni.showToast({
								    icon: 'none',
								    title: data.message
								  });
							  }
					      })
					      .catch(err => {
					        uni.showToast({
					          icon: 'none',
					          title: '保存失败，请检查接口返回'
					        });
					      });
				}).catch(err => {
					console.log('err', err);
				})
			},
			getData() {
				postForm('/problem/selectById', {id: this.id} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							this.FormData = data.data
							if(this.FormData.abarbeitungTime == null) {
								this.FormData.abarbeitungTime = Date.now()
							}
							//this.getUser()
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			getUser() {
				postForm('/user/selectById', {id: this.userId} )
				    .then(data => {
						if(data.code == 200) {
							this.FormData.checkUserId = data.data.name
							//console.log(this.FormData.checkUserId)
							//debugger
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			  goBack() {
				uni.switchTab({
					url: '/pages/position/handel/index' // 跳转页面的路径
				});
			  },
			//文件上传
			async onFileChange(event) {
				//console.log(event,'event')
				//debugger
				try {
				  const files = event.tempFiles; // 获取选择的文件列表
				  
				  if (!files || files.length === 0) {
				    uni.showToast({
				      title: '请选择文件',
				      icon: 'none',
				      duration: 2000
				    });
				    return;
				  }
					const filePath = files[0].path; // 获取文件路径
				    
				    // 显示加载提示
				    uni.showLoading({
				      title: '上传中...',
				      mask: true
				    });
				
				    // 使用 fileUpLoad 上传文件
				    let response = await fileUpLoad('/alone/uploadImages', filePath);
				    
				    // 隐藏加载提示
				    uni.hideLoading();
				    // response 现在可能是文件URL字符串或后端返回的 data 对象
				    let fileUrl = response;
				    /* if (typeof response === 'object' && response.url) {
				      fileUrl = response.url; // 如果是对象，提取 URL
				    } */
				
				    if (fileUrl) {
				      // 存储上传文件的URL
					  this.FormData.frontImage = fileUrl
				      //this.uploadedFiles.push(fileUrl);
				      
				      uni.showToast({
				        title: '上传成功',
				        icon: 'success',
				        duration: 2000
				      });
				    }
				} catch (error) {
				  uni.hideLoading();
				  uni.showToast({
				    title: '上传失败，请重试',
				    icon: 'none',
				    duration: 2000
				  });
				  console.error('文件上传错误:', error);
				}
			},
			previewImage(url) {
				let img = []
				img[0] = url
				uni.previewImage({
					current: 0,
				    urls: img // 图片列表
				    });
			},
		    change(e) {
				this.FormData.createTime = e
				console.log('change事件:', this.single = e);
			},
			selChange() {},		
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			maskClick(e){
				console.log('maskClick事件:', e);
			}
		}
	}
</script>

<style>
	
	.uni-imge {
		height: 70px;
		width: 70px;
	}
	.is-disabled {
	    color: #000 !important;
	}
	/* uni-form  lable样式 */
	.uni-forms-item__label {
		font-weight: 600 !important;
		width: 80px !important;
	  text-align: right !important;
	  justify-content: flex-end !important;
	}
	.uni-button-color {
		background-color: #007aff !important;
	}
</style>
